from flask import Blueprint, render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from models.finance import Settlement, Payment
from extensions import db
from datetime import datetime
import uuid

finance_bp = Blueprint('finance', __name__)

@finance_bp.route('/settlements')
@login_required
def settlement_list():
    # 获取查询参数
    order_id = request.args.get('order_id', '')
    customer_name = request.args.get('customer_name', '')
    status = request.args.get('status', '')
    payment_status = request.args.get('payment_status', '')
    
    # 构建查询
    query = Settlement.query
    if order_id:
        query = query.filter(Settlement.order_id.like(f'%{order_id}%'))
    if customer_name:
        query = query.filter(Settlement.customer_name.like(f'%{customer_name}%'))
    if status:
        query = query.filter(Settlement.status == status)
    if payment_status:
        query = query.filter(Settlement.payment_status == payment_status)
    
    # 分页
    page = request.args.get('page', 1, type=int)
    pagination = query.order_by(Settlement.created_at.desc()).paginate(
        page=page, per_page=10, error_out=False)
    
    return render_template('finance/settlement_list.html',
                         settlements=pagination.items,
                         pagination=pagination,
                         order_id=order_id,
                         customer_name=customer_name,
                         status=status,
                         payment_status=payment_status)

@finance_bp.route('/settlements/add', methods=['GET', 'POST'])
@login_required
def settlement_add():
    if request.method == 'POST':
        settlement = Settlement(
            order_id=request.form.get('order_id'),
            settlement_no=f"ST{datetime.now().strftime('%Y%m%d%H%M%S')}{str(uuid.uuid4())[:8]}",
            customer_name=request.form.get('customer_name'),
            amount=request.form.get('amount'),
            settlement_type=request.form.get('settlement_type'),
            payment_method=request.form.get('payment_method'),
            notes=request.form.get('notes'),
            created_by=current_user.id
        )
        db.session.add(settlement)
        db.session.commit()
        flash('结算记录创建成功', 'success')
        return redirect(url_for('finance.settlement_list'))
    return render_template('finance/settlement_add.html')

@finance_bp.route('/settlements/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def settlement_edit(id):
    settlement = Settlement.query.get_or_404(id)
    if request.method == 'POST':
        settlement.customer_name = request.form.get('customer_name')
        settlement.amount = request.form.get('amount')
        settlement.settlement_type = request.form.get('settlement_type')
        settlement.status = request.form.get('status')
        settlement.payment_method = request.form.get('payment_method')
        settlement.notes = request.form.get('notes')
        settlement.handler_id = current_user.id
        
        db.session.commit()
        flash('结算记录更新成功', 'success')
        return redirect(url_for('finance.settlement_list'))
    return render_template('finance/settlement_edit.html', settlement=settlement)

@finance_bp.route('/payments')
@login_required
def payment_list():
    # 获取查询参数
    settlement_id = request.args.get('settlement_id', '')
    payment_method = request.args.get('payment_method', '')
    status = request.args.get('status', '')
    
    # 构建查询
    query = Payment.query
    if settlement_id:
        query = query.filter(Payment.settlement_id == settlement_id)
    if payment_method:
        query = query.filter(Payment.payment_method == payment_method)
    if status:
        query = query.filter(Payment.status == status)
    
    # 分页
    page = request.args.get('page', 1, type=int)
    pagination = query.order_by(Payment.created_at.desc()).paginate(
        page=page, per_page=10, error_out=False)
    
    return render_template('finance/payment_list.html',
                         payments=pagination.items,
                         pagination=pagination,
                         settlement_id=settlement_id,
                         payment_method=payment_method,
                         status=status)

@finance_bp.route('/payments/add', methods=['GET', 'POST'])
@login_required
def payment_add():
    if request.method == 'POST':
        payment = Payment(
            settlement_id=request.form.get('settlement_id'),
            payment_no=f"PAY{datetime.now().strftime('%Y%m%d%H%M%S')}{str(uuid.uuid4())[:8]}",
            amount=request.form.get('amount'),
            payment_method=request.form.get('payment_method'),
            payment_time=datetime.strptime(request.form.get('payment_time'), '%Y-%m-%dT%H:%M'),
            transaction_id=request.form.get('transaction_id'),
            notes=request.form.get('notes'),
            created_by=current_user.id
        )
        
        # 更新结算记录的支付状态
        settlement = Settlement.query.get(payment.settlement_id)
        if settlement:
            settlement.paid_amount = float(settlement.paid_amount or 0) + float(payment.amount)
            if float(settlement.paid_amount) >= float(settlement.amount):
                settlement.payment_status = 'paid'
            elif float(settlement.paid_amount) > 0:
                settlement.payment_status = 'partial'
        
        db.session.add(payment)
        db.session.commit()
        flash('付款记录创建成功', 'success')
        return redirect(url_for('finance.payment_list'))
    return render_template('finance/payment_add.html') 